package com.example.featuresdk.navigation

import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import com.example.featuresdk.core.AbstractFeatureSDK

class NavigationController : INavigationController {

    private constructor()
    companion object{
        val instance = NavigationController()
    }

    var featureSDKs: List<AbstractFeatureSDK> = emptyList()

    var navController: NavHostController? = null
        internal set

    override fun back(){
        navController?.popBackStack()
    }

    override fun getNavigationRoutes(): List<String> = emptyList()

    override fun navigate(route: String, vararg params: String) {

        //navigate to the destination specified by the 'route' parameter
        navController?.navigate(route) {

            // Pop up to the start destination of the graph to
            // avoid building up a large stack of destinations
            // on the back stack as users select items
            popUpTo(navController?.graph?.findStartDestination()?.id!!) {
                // save the back stack and state of all destinations between the current
                // destination and the start destination for later restoration via 'restoreState = true'
                saveState = true

                //keep the start destination in the back stack,
                // otherwise we can't restore its state when revisit the destination
                inclusive = false
            }

            // launch to the destination as single-top
            // i.e. there will be at most one copy of the given destination on the top of the back stack
            // to avoid multiple copies of the same destination when re-selecting the same tab entry
            launchSingleTop = true

            //Restore any state previously saved by the PopupToBuilder.saveState for the destination.
            //Please note that the destination needs to still exist in the back stack,
            //otherwise it will raise an IllegalStateException
            restoreState = true
        }
    }
}